package com.info.zhiduoduo.wxsdk.utils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class HttpUtil {

	/**
	 向指定URL发送GET方法的请求

	 @param url 发送请求的URL
	 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
	 @return URL 所代表远程资源的响应结果
	 */
	public static String sendGet(String url) {
		String result = "";
		HttpURLConnection connection = null;
		BufferedReader in = null;
		try {
			String urlNameString = url;
			URL realUrl = new URL(urlNameString);
			LogUtil.info("sendGet : URL realUrl = new URL(urlNameString);");
			// 打开和URL之间的连接
			connection = (HttpURLConnection) realUrl.openConnection();
			LogUtil.info("sendGet : connection = (HttpURLConnection) realUrl.openConnection();");
			// 设置连接主机服务器的超时时间：15000毫秒
			connection.setConnectTimeout(15000);
			// 设置读取远程返回的数据时间：60000毫秒
			connection.setReadTimeout(60000);
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
			LogUtil.info("sendGet : connection.set...();");
			// 建立实际的连接
			connection.connect();
			LogUtil.info("sendGet : connection.connect();");
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			LogUtil.info("sendGet : Map<String, List<String>> map = connection.getHeaderFields();");
			// 遍历所有的响应头字段
			// 定义 BufferedReader输入流来读取URL的响应
			int respCode = connection.getResponseCode();
			LogUtil.info("sendGet : int respCode = connection.getResponseCode();  respCode = " + respCode);
			if (respCode >= 400) {
				in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
				LogUtil.info("sendGet : in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));");
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
				LogUtil.info("http [" + url + "] errorcode [" + respCode + "] result:" + result);
			} else {
				in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				LogUtil.info("sendGet : in = new BufferedReader(new InputStreamReader(connection.getInputStream()));");
				String line;
				while ((line = in.readLine()) != null) {
					result += line;
				}
				LogUtil.info("sendGet : http result = " + result);
			}
		} catch (Exception e) {
			LogUtil.info("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
					LogUtil.info("finally try : in.close();");
				}
				if (connection != null) {
					connection.disconnect();
					connection = null;
					LogUtil.info("finally try : connection.disconnect();");
				}
			} catch (Exception e2) {
				LogUtil.info("finally catch exception : " + e2);
				e2.printStackTrace();
			}
		}
		LogUtil.info("sendGet result : " + result);
		return result;
	}

	/**
	 向指定url 发送post方式的请求

	 @param url
	 @param sendData
	 @return
	 */
	public static String postData(String url, String sendData) {
		String responsorUrl = url;

		HttpURLConnection urlConnection = null;
		try {
			URL aURL = new URL(responsorUrl);

			urlConnection = (HttpURLConnection) aURL.openConnection();
			// 设置连接主机服务器的超时时间：15000毫秒
			urlConnection.setConnectTimeout(15000);
			// 设置读取远程返回的数据时间：60000毫秒
			urlConnection.setReadTimeout(60000);
			urlConnection.setRequestMethod("POST");
			urlConnection.setDoInput(true);
			urlConnection.setDoOutput(true);
			urlConnection.setUseCaches(false);
			urlConnection.setRequestProperty("User-Agent", "MSIE");
			urlConnection.setRequestProperty("Content-Type","application/json");
			urlConnection.connect();
			if (sendData != null && sendData.trim().length() != 0) {
				urlConnection.getOutputStream().write(sendData.getBytes("utf-8"));
			}

			int contentLen = urlConnection.getContentLength();

			java.io.DataInputStream in = new java.io.DataInputStream(urlConnection.getInputStream());

			byte buffer[] = new byte[contentLen];

			int len = 0;

			while (len < contentLen) {
				int remainedLen = contentLen - len;
				if (remainedLen > 1024)
					remainedLen = 1024;
				int readLen = in.read(buffer, len, remainedLen);
				if (readLen == -1 || readLen == 0) {
					break;
				}

				len = len + readLen;
			}

			urlConnection.disconnect();
			urlConnection = null;
			String a = new String(buffer, 0, contentLen, "utf8");

			return a;

		} catch (Throwable e) {
			LogUtil.info("发送post请求出现异常！" + e);
			e.printStackTrace();
			if (urlConnection != null) {
				try {
					urlConnection.disconnect();
					urlConnection = null;
				} catch (Exception ee) {
					ee.printStackTrace();
				}
			}
		} finally {
			if (urlConnection != null) {
				try {
					urlConnection.disconnect();
					urlConnection = null;
				} catch (Exception ee) {
				}
			}
		}
		return "";
	}

	/**
	 get请求,当返回数据为空或报错时,自动重试3次

	 @param url
	 @return
	 */
	public static String sendGetWithRetry(String url) {
		String res = "";
		for (int i = 0; i < 3; i++) {
			try {
				res = sendGet(url);
				if (!StringUtil.isEmpty(res)) {
					break;
				}
			} catch (Exception e) {
				LogUtil.info("sendGetWithRetry 报错 : " + e.getMessage());
			}
		}
		return res;
	}

	/**
	 post请求,当返回数据为空或报错时,自动重试3次

	 @param url
	 @param data
	 @return
	 */
	public static String postDataWithRetry(String url, String data) {
		String res = "";
		for (int i = 0; i < 3; i++) {
			try {
				res = postData(url, data);
				if (!StringUtil.isEmpty(res)) {
					break;
				}
			} catch (Exception e) {
				LogUtil.info("postDataWithRetry 报错 : " + e.getMessage());
			}
		}
		return res;
	}
}
